﻿Imports System.Threading
Imports System.Net.Sockets
Imports System.IO
Imports System.Net

Imports System
Imports System.ComponentModel
Imports System.Windows.Forms
Public Class MainForm
    Dim WithEvents oMessage As Receive
    Dim WithEvents nMessageSpawned As News
    Public Shared t As Thread
    Public Shared t2 As Thread
    Public Shared n As Thread
    Private Delegate Sub WriteMessageCallback(ByVal Write As Object)
    Private Delegate Sub NewsMsgCallback(ByVal News As Object)
    Private Delegate Sub SetTextCallback(ByVal MessageReceived As Object)
    Dim RightClickedItem As ListViewItem
    Dim ListItem As ListViewItem

    Public Sub Shutdown() Handles Me.Disposed
        Dim TimeInfo As DateTime = DateTime.Now
        'converts time to string
        Dim Time As String = TimeInfo.ToString("T")
        'pads time string to 11 chars
        Dim TimePad As String = Time.PadRight(11)
        TextHandling.QueueMessage("", "/logout", "Normal Outgoing")
        TextHandling.LogMessage("<font font=Calibri size=2 color=#D3D3D3>" + TimePad + " </font> " + " <font font=Calibri size=2 color=" & TextHandling.GetHexColor(Drawing.Color.FromName(Skin.SystemColor)) & ">&nbsp;Bot is shutting down. Saving remaining log messages.</font><br>", True)
        Application.Exit()
    End Sub

    Private Sub SendBut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendBut.Click
        If InputTextBox.Text <> "" Then
            If BNetworking.T.Connected = True Then
                TextHandling.QueueMessage("", InputTextBox.Text, "Normal Outgoing", True)
            Else
                TextHandling.QueueMessage("", "The bot is not connected to a server. Please login or relogin before sending more messages.", "System")
            End If
        End If
        InputTextBox.Clear()
    End Sub

    Private Sub InputBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles InputTextBox.KeyPress
        If e.KeyChar = vbCr Then
            SendBut_Click(Me, EventArgs.Empty)
            e.Handled = True
        End If
    End Sub

    Private Sub SetText(ByVal MessageReceived As String) Handles oMessage.ThreadComplete
        If Me.ChatRichBox.InvokeRequired Then
            ' It's on a different thread, so use Invoke.
            Dim d As New SetTextCallback(AddressOf SafeAdd)
            Me.Invoke(d, MessageReceived)
        Else
            ' It's on the same thread, no need for Invoke.
            TextHandling.SelectType(MessageReceived)
        End If
    End Sub

    Public Sub SafeAdd(ByVal MessageReceived As Object)
        TextHandling.SelectType(MessageReceived)
        'Me.ChatBox.AppendText(Square)
    End Sub

    Public Sub AddUser(ByVal UserName As Object, ByVal Rank As Object, ByVal Tag As Object)
        Select Case Rank
            Case "0000"
                'normal user
                Select Case Tag
                    Case "CHAT"
                        'telnet chat
                        'UserBox.Items.Add(UserName, 4)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 4)
                    Case "WAR3"
                        'UserBox.Items.Add(UserName, 12)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 12)
                    Case "W3XP"
                        'tft
                        'UserBox.Items.Add(UserName, 13)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 13)
                    Case "DSHR"
                        'Diablo 1 shareware (unsure)
                        'UserBox.Items.Add(UserName, 5)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 5)
                    Case "DRTL"
                        'Diablo 1 retail (unsure)
                        'UserBox.Items.Add(UserName, 5)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 5)
                    Case "D2DV"
                        'original
                        'UserBox.Items.Add(UserName, 6)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 6)
                    Case "D2XP"
                        'expansion
                        'UserBox.Items.Add(UserName, 7)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 7)
                    Case "SSHR"
                        'starcraft shareware (unsure)
                        'UserBox.Items.Add(UserName, 14)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 10)
                    Case "STAR"
                        'starcraft
                        'UserBox.Items.Add(UserName, 14)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 14)
                    Case "SEXP"
                        'UserBox.Items.Add(UserName, 15)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 15)
                    Case "W2BN"
                        'UserBox.Items.Add(UserName, 10)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 10)
                    Case Else
                        'UserBox.Items.Add(UserName, 11)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 11)
                End Select
            Case "0001"
                'blizzard rep
                'UserBox.Items.Add(UserName, 0)
                ColumnHeader1.ListView.Items.Insert(0, UserName, 0)
                Dim UserNameLVI As ListViewItem = UserBox.FindItemWithText(UserName)
                UserNameLVI.ForeColor = Color.CornflowerBlue
            Case "0002"
                'channel op (tmpop maybe)?
                'UserBox.Items.Add(UserName, 1)
                Select Case Tag
                    Case "CHAT"
                        'telnet chat
                        'UserBox.Items.Add(UserName, 4)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 4)
                    Case "WAR3"
                        'UserBox.Items.Add(UserName, 12)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 12)
                    Case "W3XP"
                        'tft
                        'UserBox.Items.Add(UserName, 13)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 13)
                    Case "DSHR"
                        'Diablo 1 shareware (unsure)
                        'UserBox.Items.Add(UserName, 5)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 5)
                    Case "DRTL"
                        'Diablo 1 retail (unsure)
                        'UserBox.Items.Add(UserName, 5)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 5)
                    Case "D2DV"
                        'original
                        'UserBox.Items.Add(UserName, 6)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 6)
                    Case "D2XP"
                        'expansion
                        'UserBox.Items.Add(UserName, 7)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 7)
                    Case "SSHR"
                        'starcraft shareware (unsure)
                        'UserBox.Items.Add(UserName, 14)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 10)
                    Case "STAR"
                        'starcraft
                        'UserBox.Items.Add(UserName, 14)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 14)
                    Case "SEXP"
                        'UserBox.Items.Add(UserName, 15)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 15)
                    Case "W2BN"
                        'UserBox.Items.Add(UserName, 10)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 10)
                    Case Else
                        'UserBox.Items.Add(UserName, 11)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 11)
                End Select
                Dim UserNameLVI As ListViewItem = UserBox.FindItemWithText(UserName)
                UserNameLVI.ForeColor = Color.Gold
            Case "0004"
                'voiced
                'UserBox.Items.Add(UserName, 2)
                ColumnHeader1.ListView.Items.Insert(0, UserName, 2)
                Dim UserNameLVI As ListViewItem = UserBox.FindItemWithText(UserName)
                UserNameLVI.ForeColor = Color.Violet
            Case "0008"
                'admin
                'UserBox.Items.Add(UserName, 1)
                ColumnHeader1.ListView.Items.Insert(0, UserName, 1)
                Dim UserNameLVI As ListViewItem = UserBox.FindItemWithText(UserName)
                UserNameLVI.ForeColor = Color.CornflowerBlue
            Case "0010"
                'no udp - same as 0000
                Select Case Tag
                    Case "CHAT"
                        'telnet chat
                        'UserBox.Items.Add(UserName, 4)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 4)
                    Case "WAR3"
                        'UserBox.Items.Add(UserName, 12)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 12)
                    Case "W3XP"
                        'tft
                        'UserBox.Items.Add(UserName, 13)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 13)
                    Case "DSHR"
                        'Diablo 1 shareware (unsure)
                        'UserBox.Items.Add(UserName, 5)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 5)
                    Case "DRTL"
                        'Diablo 1 retail (unsure)
                        'UserBox.Items.Add(UserName, 5)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 5)
                    Case "D2DV"
                        'original
                        'UserBox.Items.Add(UserName, 6)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 6)
                    Case "D2XP"
                        'expansion
                        'UserBox.Items.Add(UserName, 7)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 7)
                    Case "SSHR"
                        'starcraft shareware (unsure)
                        'UserBox.Items.Add(UserName, 14)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 10)
                    Case "STAR"
                        'starcraft
                        'UserBox.Items.Add(UserName, 14)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 14)
                    Case "SEXP"
                        'UserBox.Items.Add(UserName, 15)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 15)
                    Case "W2BN"
                        'UserBox.Items.Add(UserName, 10)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 10)
                    Case Else
                        'UserBox.Items.Add(UserName, 11)
                        ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 11)
                End Select
            Case "0020"
                'squelched
                'UserBox.Items.Add(UserName, 3)
                ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 3)
            Case Else
                'UserBox.Items.Add(UserName, 11)
                ColumnHeader1.ListView.Items.Insert(UserBox.Items.Count, UserName, 11)
        End Select
        Dim UserNameTAG As ListViewItem = UserBox.FindItemWithText(UserName)
        UserNameTAG.Tag = Tag
    End Sub

    Public Sub DelUser(ByVal Square As Object)
        Me.UserBox.Items.RemoveAt(Square)
        'Me.ChatBox.AppendText(Square)
    End Sub

    Public Sub LoginLogoutBut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoginLogoutBut.Click
        If BNetworking.T.Connected = False Then
            BNetworking.Connect()

            oMessage = New Receive()
            t = New Thread(AddressOf oMessage.Receive)
            t.SetApartmentState(ApartmentState.MTA)
            t.Start()

            't2 = New Thread(AddressOf oMessage.Process)
            't2.SetApartmentState(ApartmentState.MTA)
            't2.Start()

            BNetworking.WriteMessageThread = New Thread(AddressOf BNetworking.WriteMessageT)
            BNetworking.WriteMessageThread.Start()
        Else
            BNetworking.ConnectionClosed()
            TextHandling.QueueMessage("", "Logging out. Disconnected from server.", "System")
            LoginLogoutBut.Text = "Login"
        End If
    End Sub

    Private Sub ExitBut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitBut.Click
        Application.Exit()
    End Sub

    Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AntiIdleTimer.Start()
        CreateMissingDIR()

        Dim f As New IO.DirectoryInfo("logs")
        If f.Exists = False Then
            IO.Directory.CreateDirectory("logs")
        End If
        Me.Text = Settings.Version
        Settings.CreateSettings()
        Settings.ParseSettings()

        Skin.CreateSkin(Settings.DefaultSkin)
        Skin.LoadSkin(Settings.DefaultSkin)

        If Settings.LoggingStatus = "0" Then
            TextHandling.QueueMessage("", "Text logging system is disabled.", "System")
        ElseIf Settings.LoggingStatus = "1" Then
            TextHandling.QueueMessage("", "Text logging system is enabled.", "System")
        Else
            TextHandling.QueueMessage("", "Misconfiguration Detected. Please Set LoggingStatus to either 0 for off or 1 for on in settings.ini.", "System")
        End If

        nMessageSpawned = New News()
        n = New Thread(AddressOf nMessageSpawned.LoadNews)
        n.Start()

        If Settings.AutoLogin = "1" Then
            LoginLogoutBut_Click(Me, EventArgs.Empty)
        End If
    End Sub

    Private Sub SwitchBut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SwitchBut.Click
        SwitchUserForm.Show()
    End Sub

    Private Sub NewsMsg(ByVal MessageReceived As String) Handles nMessageSpawned.NewsMessageSpawned
        'TextHandling.SelectType(Square)
        If Me.ChatRichBox.InvokeRequired Then
            ' It's on a different thread, so use Invoke.
            Dim d As New NewsMsgCallback(AddressOf NewsAdd)
            Me.Invoke(d, MessageReceived)
            'Me.Invoke(d, New Object() {Square})
        Else
            ' It's on the same thread, no need for Invoke.
            TextHandling.QueueMessage("", MessageReceived, "Info")
            'Me.ChatBox.AppendText(Square)
        End If
    End Sub

    Private Sub NewsAdd(ByVal MessageReceived As Object)
        TextHandling.QueueMessage("", MessageReceived, "Info")
        'Me.ChatBox.AppendText(Square)
    End Sub

    Private Sub NewsBut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewsBut.Click
        nMessageSpawned = New News()
        n = New Thread(AddressOf nMessageSpawned.LoadNews)
        n.Start()
    End Sub

    Private Sub InputTextBox_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles InputTextBox.KeyDown
        If e.KeyCode = Keys.Up Then
            'Go to last Message Sent
        End If

        If e.KeyCode = Keys.Down Then
            'Go to last Message Sent
        End If

        If e.KeyCode = Keys.V AndAlso (e.Modifiers And Keys.Control) <> Keys.None Then
            Dim Cliptext As String = Clipboard.GetText
            Dim ClipArray As String() = Cliptext.Split((Chr(13)))
            Dim ClipLength As Integer = ClipArray.Length()
            Dim ClipNo As Integer = 0
            If ClipLength > 1 Then
                While ClipLength > 0
                    TextHandling.QueueMessage("", ClipArray(ClipNo).Replace(Chr(10), ""), "Normal Outgoing", True)
                    ClipLength = ClipLength - 1
                    ClipNo = ClipNo + 1
                End While
                ClearInput()
            End If
        End If
    End Sub

    Private Sub ClearInput()
        InputTextBox.Clear()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AntiIdleTimer.Tick
        If BNetworking.T.Connected Then
            Dim WriteMessager As BNetworking = New BNetworking()
            WriteMessager.WriteMessage("/join " + Settings.CurrentChannel)
        Else
            If LoginLogoutBut.Text = "Logout" Then
                BNetworking.ConnectionClosed()
                TextHandling.QueueMessage("", "Connection Lost. Please Relogin.", "Error")
                LoginLogoutBut.Text = "Login"
            End If
        End If
    End Sub

    Private Sub CreateMissingDIR()
        If Directory.Exists("skins") = False Then
            Directory.CreateDirectory("skins\")
        End If
        If Directory.Exists("commands") = False Then
            Directory.CreateDirectory("commands\")
        End If
        If Directory.Exists("logs") = False Then
            Directory.CreateDirectory("logs\")
        End If
    End Sub

    Private Sub FingerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FingerToolStripMenuItem.Click
        If Not IsNothing(RightClickedItem) Then
            TextHandling.QueueMessage("", "/finger " & RightClickedItem.Text, "Normal Outgoing")
        End If
    End Sub

    Private Sub PingToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PingToolStripMenuItem.Click
        If Not IsNothing(RightClickedItem) Then
            TextHandling.QueueMessage("", "/ping " & RightClickedItem.Text, "Normal Outgoing")
        End If
    End Sub

    Private Sub ProfileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProfileToolStripMenuItem.Click
        If Not IsNothing(RightClickedItem) Then
            TextHandling.QueueMessage("", "/finger " & RightClickedItem.Text, "Normal Outgoing")
        End If
    End Sub

    Public Sub UserBox_Click(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles UserBox.MouseClick
        If e.Button = MouseButtons.Right Then
            RightClickedItem = UserBox.GetItemAt(e.X, e.Y)
        End If
        If e.Button = Windows.Forms.MouseButtons.Left Then
            ListItem = UserBox.GetItemAt(e.X, e.Y)
        End If
    End Sub

    Public Sub UserBox_DoubleClick() Handles UserBox.DoubleClick
        If Not ListItem Is Nothing Then
            InputTextBox.Text = "/w " & ListItem.Text & " "
            InputTextBox.Select()
        End If
    End Sub
End Class
